package com.service;

import com.constant.RedisKey;
import com.dao.UserDao;
import com.dto.PwdDTO;
import com.po.UserPO;
import com.util.*;
import dto.UserDTO;
import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * @author linyukun
 * @date 2022/7/6 18:26
 */
@Service
public class UserServiceImpl {
    @Autowired
    private SendCodeServiceImpl sendCodeServiceImpl;

    @Value("${system.redis.key.days.uid}")
    private long maxDays;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserDao userDao;


    public UserPO doLogin(UserDTO userDTO, HttpServletRequest request) {
        if(StringUtils.isBlank(userDTO.getUserName())){
            throw new RestException("请传递账号");
        }
        if(StringUtils.isBlank(userDTO.getPassword())){
            throw new RestException("请传递密码");
        }
        if(StringUtils.isBlank(userDTO.getVerificationCode())){
            throw new RestException("请传递验证码");
        }
        //region 校验验证码
        sendCodeServiceImpl.checkCode(userDTO.getVerificationCode(),IpUtils.getClientIpAddress(request));
        //endregion 校验验证码

        UserPO userPO = userDao.getUserByUserName(userDTO.getUserName());
        if(ObjectUtils.isEmpty(userPO)){
            throw new RestException("找不到用户");
        }
        if(!userPO.getPassword().equals(userDTO.getPassword())){
            throw new RestException("密码不正确");
        }
        String userToken = "";
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis()));
        userToken = Md5Util.getMd5Len32(userPO.getUserName() + userPO.getPassword() + date);
        String userTokenKey = RedisKey.LIBRARY_USER_TOKEN + userToken;
        String userNameKey = RedisKey.LIBRARY_USER_USERNAME + userPO.getUserName();


        String adminJson = redisUtil.get( userNameKey );//从token里面获取数据
        if( StringUtils.isNotBlank( adminJson ) ){//判断uid
            UserPO result = JSONUtils.parse( adminJson , UserPO.class );
            if(!ObjectUtils.isEmpty(result)){//不为空
                String tokenTemp = result.getUserToken();
                if(!StringUtils.isEmpty(tokenTemp)){//不为空
                    redisUtil.delete(RedisKey.LIBRARY_USER_TOKEN + tokenTemp );
                }
            }
        }

        userPO.setUserToken(userToken);
        redisUtil.setByDays(userNameKey, JSONUtils.toString(userPO) , maxDays);//这个是userName的key
        redisUtil.setByDays(userTokenKey,JSONUtils.toString(userPO) , maxDays);//这个是token的缓存

        //登录成功
        return userPO;
    }

    public void outLogin(HttpServletRequest request) {
        String token = request.getHeader("userToken");
        String tokenKey = RedisKey.LIBRARY_USER_TOKEN + token;
        String adminJson = redisUtil.get( tokenKey );//从token里面获取数据
        if( StringUtils.isNotBlank( adminJson ) ){//判断uid
            UserPO userPO = JSONUtils.parse( adminJson , UserPO.class );
            redisUtil.delete(RedisKey.LIBRARY_USER_USERNAME +  userPO.getUserName());//删除redis的token
        }
        redisUtil.delete(tokenKey );//删除redis的token
    }

    public void changePwd(PwdDTO pwdDto) {
        String userName = UserLocal.get().getUserName();
        UserPO userPO = userDao.getUserByUserName(userName);
        if(ObjectUtils.isEmpty(userPO)){
            throw new RestException("找不到用户");
        }
        if(!userPO.getPassword().equals(pwdDto.getOldPwd())){
            throw new RestException("旧密码不正确");
        }
        userDao.changePwdByUserName(userName,pwdDto.getNewPwd());

    }

    public UserPO getUserByName(PwdDTO pwdDto) {
        UserPO result = userDao.getUserByName(pwdDto.getUserName());;
        if(ObjectUtils.isEmpty(result)){
            throw new RestException("找不到用户");
        }
        return result;
    }

    public UserPO getUserByNameAll(PwdDTO pwdDto) {
        UserPO result = userDao.getUserByNameAll(pwdDto.getUserName());;
        if(ObjectUtils.isEmpty(result)){
            throw new RestException("找不到用户");
        }
        return result;
    }
}
